package cn.hnwlgc.controller;

import cn.hnwlgc.pojo.Result;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@RestController
@CrossOrigin(origins = "*")
public class UploadController {

    private final Path fileStorageLocation = Paths.get("src/main/resources/static/uploads");

    @PostMapping("/upload")
    @ResponseStatus(HttpStatus.OK)
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
        // 创建文件存储目录
        try {
            Files.createDirectories(fileStorageLocation);
        } catch (IOException e) {
            return Result.error("无法创建文件存储目录");
        }

        // 获取文件名并保存文件
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (fileName.contains("..")) {
                return Result.error("文件名包含非法路径序列");
            }

            Path targetLocation = fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            String fileDownloadUri = "/uploads/" + fileName;
            return Result.success(fileDownloadUri);
        } catch (IOException e) {
            return Result.error("无法存储文件");
        }
    }
}
